package com.springboot.killingsystem.service;

import com.springboot.killingsystem.dao.GoodsDao;
import com.springboot.killingsystem.dao.OrderDao;
import com.springboot.killingsystem.domain.OrderInfo;
import com.springboot.killingsystem.domain.SecondKillingOrder;
import com.springboot.killingsystem.domain.SecondKillingUser;
import com.springboot.killingsystem.redis.OrderKey;
import com.springboot.killingsystem.redis.RedisService;
import com.springboot.killingsystem.util.Constant;
import com.springboot.killingsystem.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
public class OrderService {

    @Autowired
    GoodsDao goodsDao;

    @Autowired
    OrderDao orderDao;

    @Autowired
    RedisService redisService;

    public SecondKillingOrder getSecondsKillingOrderByGoodsId(long userId, long goodsId) {
        return redisService.get(
                OrderKey.getSecondKillingOrderByUidGid,
                Constant.DEFAULT_KEY+userId+Constant.SPLIT_SIGNAL+goodsId,
                SecondKillingOrder.class);
    }

    @Transactional
    public OrderInfo createOrder(SecondKillingUser user, GoodsVo goods) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goods.getId());
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setGoodsPrice(goods.getMiaoshaPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setUserId(user.getId());
        orderDao.insert(orderInfo);

        SecondKillingOrder secondKillingOrder = new SecondKillingOrder();
        secondKillingOrder.setGoodsId(goods.getId());
        secondKillingOrder.setOrderId(orderInfo.getId());
        secondKillingOrder.setUserId(user.getId());
        orderDao.insertSecondKillingOrder(secondKillingOrder);

        // 缓存优化：生成的秒杀订单可以存入redis，这样以后调用getSecondsKillingOrderByGoodsId这个方法的时候可以直接从缓存中取订单信息
        redisService.set(
                OrderKey.getSecondKillingOrderByUidGid,
                Constant.DEFAULT_KEY+user.getId()+Constant.SPLIT_SIGNAL+goods.getId(),
                secondKillingOrder);

        return orderInfo;
    }

    public OrderInfo getOrderById(long orderId) {
        return orderDao.getOrderById(orderId);
    }
}
